package item15;

public final class Complex02 {

    private final double re;
    private final double im;

    public Complex02(double re, double im) {
        this.re = re;
        this.im = im;
    }

    public static Complex02 valueOf(double re, double im) {
        return new Complex02(re, im);
    }

    public static Complex02 valueOfPolar(double r, double theta) {
        return new Complex02(r * Math.cos(theta), r * Math.sin(theta));
    }

    // accessors with no corresponding mutators
    // 没有相应的mutator访问器
    public double realPart() {return re;}
    public double imaginaryPart() {return im;}

    public Complex02 add(Complex02 c) {
        return new Complex02(re + c.re, im + c.im);
    }

    public Complex02 substract(Complex02 c) {
        return new Complex02(re * c.re - im * c.im, re * c.im + im * c.re);
    }

    public Complex02 multiply(Complex02 c) {
        return new Complex02(re * c.re - im * c.im, re * c.im + im * c.re);
    }

    public Complex02 divide(Complex02 c) {
        double tmp = c.re * c.re + c.im * c.im;
        return new Complex02((re * c.re + im * c.im) / tmp, (im * c.re - re * c.im)/ tmp);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this)
            return true;
        if (!(obj instanceof Complex02))
            return false;
        Complex02 c = (Complex02) obj;
        // see page 43 to find out why we use compare instead of ==
        // 请参阅第43页，了解我们使用比较而不是==的原因
        return Double.compare(re, c.re) == 0 && Double.compare(im, c.im) == 0;
    }

    private int hashDouble(double val) {
        long longBits = Double.doubleToLongBits(re);
        return (int) (longBits ^ (longBits >>> 32));
    }

    @Override
    public int hashCode() {
        int result = 17 + hashDouble(re);
        result = 31 * result + hashDouble(im);
        return result;
    }

    @Override
    public String toString() {
        return "(" + re + " + " + im + "i)";
    }
}
